import { Button, Form, message, Modal } from 'antd';
import { WeaSearchGroup, WeaTools, WeaDialog, WeaLocaleProvider } from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import { toJS } from 'mobx';
import allStore from '../stores';

const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;


// 删除操作
const doDelete = params => WeaTools.callApi('/api/doc/operate/delete', 'GET', params);

// 得到右键菜单
// CompStore指定要使用此方法的组件自己所特有的组件，
// TableMobxStore指定WadTableMobx所有的Store
export function getRightMenu(CompStore, TableMobxStore, bool = true) {
    // const workPlanSharePersonalStore = this.props.workPlanSharePersonalStore;
    // const {comsWeaTable} = this.props;
    // const selectedRowKeys = comsWeaTable.get('selectedRowKeys');

    const { dataKey } = CompStore;
    // 无筛选条件时的table的sessionkey
    const tableKey = dataKey !== '0' ? dataKey.split('_')[0] : 'init';
    const selectedRowKeys = TableMobxStore.selectedRowKeys;

    let isDisabled = true;
    let arr = [];
    if (bool) {
        arr = [{
            key: 'add',
            icon: <i className="icon-coms-plus" />,
            content: getLabel(611, '添加'),
            onClick: (key) => {
                CompStore.openAddDialog();
                // 用于新建表格中一行数据的相关方法，若存在，也调用
                if (CompStore.pageName === 'planModul') {
                    CompStore.doNewData();
                    CompStore.setIfHideSomeAboutFieldObj();
                }
            },
        }, {
            key: 'batchDelete',
            icon: <i className="icon-coms-Batch-delete" />,
            content: getLabel(32136, '批量删除'),
            disabled: selectedRowKeys.length === 0,
            onClick: (key) => {
                let curSessionKey = CompStore.dataKey,
                    tableMobxState = TableMobxStore.state,
                    selectedRowKeys = TableMobxStore.selectedRowKeys;


                doMultiDelete(...['MyDoc', TableMobxStore.selectedRowKeys, CompStore]);
            },
        }, {
            key: 'colSet',
            icon: <i className="icon-coms-Custom" />,
            content: getLabel(382660, '显示定制列'),
            // disabled: selectedRowKeys.length === 0 ? true : false,
            onClick: (key) => {
                const dataKey = CompStore.dataKey;
                TableMobxStore.setColSetVisible(dataKey, true);
                TableMobxStore.tableColSet(dataKey, true);
            },
        }];
    } else {
        arr = [{
            key: 'batchDelete',
            icon: <i className="icon-coms-Batch-delete" />,
            content: getLabel(126174, '批量完成'),
            disabled: selectedRowKeys.length === 0,
            onClick: (key) => {
                let curSessionKey = CompStore.dataKey,
                    tableMobxState = TableMobxStore.state,
                    selectedRowKeys = TableMobxStore.selectedRowKeys;


                    doMultibatchFinish(...['MyDoc', TableMobxStore.selectedRowKeys, CompStore]);
            },
        }, {
            key: 'colSet',
            icon: <i className="icon-coms-Custom" />,
            content: getLabel(382660, '显示定制列'),
            // disabled: selectedRowKeys.length === 0 ? true : false,
            onClick: (key) => {
                const dataKey = CompStore.dataKey;
                TableMobxStore.setColSetVisible(dataKey, true);
                TableMobxStore.tableColSet(dataKey, true);
            },
        }];
    }

    // !bool && (arr.shift())
    return arr;
}

// 顶部右侧按钮组合，按钮的功能逻辑待做
// store表示将要传给它的store
export function getTopButtons(CompStore, firstButtonName, TableMobxStore) {
    // const {actions,comsWeaTable,location,responseId} = this.props;
    // console.log('responseId',responseId)

    // let curSessionKey = CompStore.dataKey,
    //     tableMobxState = TableMobxStore.state,
    //     selectedRowKeys = TableMobxStore.state[CompStore.dataKey.substring(0, 36)].selectedRowKeys;

    const { dataKey } = CompStore;
    // 无筛选条件时的table的sessionkey
    const tableKey = dataKey !== '0' ? dataKey.split('_')[0] : 'init';
    const selectedRowKeys = TableMobxStore.selectedRowKeys;

    const arr = [
        (<Button
          type="primary"
          onClick={() => {
                CompStore.openAddDialog();

                // 用于新建表格中一行数据的相关方法，若存在，也调用
                if (CompStore.pageName === 'planModul') {
                    CompStore.doNewData();
                    CompStore.setIfHideSomeAboutFieldObj();
                }
            }}
        >
            {firstButtonName}
        </Button>),

        (<Button
          type="default"
          disabled={selectedRowKeys.length === 0}
          onClick={() => {
                // console.log(toJS(TableMobxStore.state[CompStore.dataKey.substring(0, 36)].selectedRowKeys))
                doMultiDelete(...['MyDoc', TableMobxStore.selectedRowKeys, CompStore]);
            }}
        >
            {getLabel(32136, '批量删除')}
        </Button>),

    ];
    return arr;
}


// 用于获取高级搜索中的表单控件
export function getSearchs(store) {
    const FormItem = Form.Item;
    // const conditioninfo = adFormdatas.condition;
    let { form, conditioninfo } = store;
    conditioninfo = toJS(conditioninfo);
    const { isFormInit } = form;
    let group = [];
    // 获取表单的值
    const formParams = form.getFormParams();
    // isFormInit 为true，form已经初始化完成
    isFormInit && conditioninfo.map((c, i) => {
        let items = [];
        c.items.map((fields, index) => {
            items.push({
                com: (<FormItem ecId={`${this && this.props && this.props.ecId || ''}_FormItem@tu6x04@${(fields.domkey && fields.domkey[0]) ? fields.domkey[0] : `tu6x04${index}`}`}
                  label={`${fields.label}`}
                  labelCol={{ span: `${fields.labelcol}` }}
                  wrapperCol={{ span: `${fields.fieldcol}` }}
                >
                    {/* 根据 WeaSwitch 获取对应的组件 */}
                    <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@aeat29@${(fields.domkey && fields.domkey[0]) ? fields.domkey[0] : `aeat29${index}`}`} fieldConfig={fields} form={form} formParams={formParams} />
                </FormItem>),
                colSpan: 1,
            });
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@x1e0nn@${i}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />);
    });
    return group;
}

// 定义tab中点击高级搜索时的最下面的操作按钮集合
export function getTabButtonsAd(store) {
    return [
        (<Button
          type="primary"
          onClick={() => {
                // 使得高级搜索在点击搜索按钮2后也能跳转到相应的tab页
                if (store.pageName === 'workPlanExchange') {
                    const viewcondition = store.form.getFormParams().timeSag;
                    if (viewcondition == 6) {
                        store.doSearch({
                            CompParams: {
                                viewcondition: '0',
                            },
                        });
                    } else {
                        store.doSearch({
                            CompParams: {
                                viewcondition,
                            },
                        });
                    }
                } else {
                    store.doSearch();
                }

                store.setShowSearchAd(false);
            }}
        >
           {getLabel(197, '搜索')}
        </Button>),
        (<Button type="ghost" onClick={() => { store.resetAdSearchForm(); }}>{getLabel(2022, '重置')}</Button>),
        (<Button type="ghost" onClick={() => { store.setShowSearchAd(false); }}>{getLabel(31129, '取消')}</Button>),
    ];
}

// 批量删除
export const doMultiDelete = (module, params, store) => {
    let ids;
    if (typeof params === 'string') {
        ids = params.split(',');
    } else {
        ids = params;
    }


    let success = [];
    let error = [];


    confirm({
        title: getLabel(131329, '信息确认'),
        content: (<span style={{ color: 'red' }}>{getLabel(15097, '确定要删除吗？')}</span>),
        onOk() {
            for (var i = 0; i < ids.length; i++) {
                let rdata = store.interfaceOfDeleteTableData({ workid: ids[i], isSys: 0 }).then((rdata) => {
                    if (rdata.status == 1) {
                        success.push(rdata);
                    } else {
                        error.push(rdata);
                    }

                    if (success.length + error.length == ids.length) {
                        if (error.length > 0) {
                            for (let j = 0; i < error.length; j++) {
                                message.error(getLabel(20462, '删除失败'));
                            }
                        } else {
                            message.success(getLabel(20461, '删除成功'));
                            // window.store_e9_element.dispatch(ComsAction.doSearch(module));
                            // 这个应该要变为mobx的store里的dosearch
                            store.doSearch();
                        }
                    }
                });
            }
        },
        onCancel() {},
    });
};
// 批量完成
export const doMultibatchFinish = (module, params, store) => {
    let ids = toJS(params).join(',');
    confirm({
        title: getLabel(131329, '信息确认'),
        content: (<span style={{ color: 'red' }}>{getLabel(126220, '确定要完成吗？')}</span>),
        onOk() {
            store.batchFinish(ids);
        },
        onCancel() {},
    });
};
